<template>
  <div>
    <DynamicTable
      row-key="id"
      header-title="TODO管理"
      :data-request="Api.businessTodo.todoList"
      :columns="columns"
      bordered
      size="small"
    >
      <template #toolbar>
        <a-button
          type="primary"
          :disabled="!$auth('todo:create')"
          @click="openMenuModal({})"
        >
          新增
        </a-button>
        <a-button type="primary" @click="importExcel()"> 导入 </a-button>
        <a-button type="primary" @click="exportExcel()"> 导出 </a-button>
      </template>
    </DynamicTable>
    <DraggableModal
      v-model:open="importVis"
      title="导入表格数据"
      @ok="onOk"
      @cancel="onCancel"
    >
      <FileUpload ref="FileUploadRef" v-model:fileData="fileData" />
      <div class="download-template" @click="downloadTemplate">下载模板</div>
    </DraggableModal>
  </div>
</template>

<script lang="ts" setup>
import {
  baseColumns,
  searchFormSchema,
  type TableColumnItem,
  type TableListItem,
} from './columns';
import { useTable } from '@/components/core/dynamic-table';
import { useFormModal } from '@/hooks/useModal/';
import { todoSchemas } from './formSchemas';
import { downloadFileWithFetch } from '@/utils/downloadFile';
import { DraggableModal } from '@/components/core/draggable-modal';
import FileUpload from './FileUpload.vue';
import { message, Upload } from 'ant-design-vue';
import { ref } from 'vue';
import Api from '@/api/';

defineOptions({
  name: 'ToDo',
});

const importVis = ref(false);
const fileData = ref<any>();
const FileUploadRef = ref();

const onOk = async () => {
  console.log('onOk', fileData.value);
  if (fileData.value && fileData.value.length > 0) {
    const res = await Api.businessTodo.todoExcelImportSaveData({
      jsonData: fileData.value,
    });
    console.log(res);
    importVis.value = false;
    if (FileUploadRef.value) {
      FileUploadRef.value.init();
    }
    dynamicTableInstance?.reload();
  } else {
    message.error('没有要导入的数据');
  }
};

const onCancel = async () => {
  if (FileUploadRef.value) {
    FileUploadRef.value.init();
  }
};

const [DynamicTable, dynamicTableInstance] = useTable({
  formProps: {
    schemas: searchFormSchema,
  },
});

const [showModal] = useFormModal();

const columns: TableColumnItem[] = [
  ...baseColumns,
  {
    title: '操作',
    width: 80,
    dataIndex: 'ACTION',
    hideInSearch: true,
    fixed: 'right',
    actions: ({ record }) => [
      {
        label: record.status ? '重新打开' : '完成',
        auth: {
          perm: 'todo:update',
          effect: 'disable',
        },
        onClick: () => {
          finishedTodo(record);
        },
      },
      {
        label: '编辑',
        auth: {
          perm: 'todo:update',
          effect: 'disable',
        },
        onClick: () => {
          openMenuModal(record);
        },
      },
      {
        label: '删除',
        auth: {
          perm: 'todo:update',
          effect: 'disable',
        },
        onClick: () => {
          deleteTodo(record);
        },
      },
    ],
  },
];

/**
 * @description 打开新增/编辑弹窗
 */
const openMenuModal = async (record: Partial<TableListItem>) => {
  const [formRef] = await showModal({
    modalProps: {
      title: `${record.id ? '编辑' : '新增'}ToDo`,
      width: '50%',
      onFinish: async values => {
        const params = {
          ...values,
        };
        if (record.id) {
          await Api.businessTodo.todoUpdate({ id: record.id }, params);
        } else {
          await Api.businessTodo.todoCreate(params);
        }

        dynamicTableInstance?.reload();
      },
    },
    formProps: {
      labelWidth: 100,
      schemas: todoSchemas,
    },
  });
  if (record.id) {
    const { value } = await Api.businessTodo.todoInfo({ id: record.id });
    formRef?.setFieldsValue({
      ...record,
    });
  }
};
const finishedTodo = async record => {
  await Api.businessTodo.todoUpdate(
    { id: record.id },
    {
      status: !record.status,
    }
  );
  dynamicTableInstance?.reload();
};

//删除某个ToDo
const deleteTodo = async record => {
  await Api.businessTodo.todoDelete({ id: record.id });
  dynamicTableInstance?.reload();
};

//导入ToDo
const importExcel = () => {
  importVis.value = true;
};
//导出ToDo
const exportExcel = async () => {
  const url = await Api.businessTodo.todoExcelExport();
  const path = import.meta.env.VITE_BASE_URL + url;
  downloadFileWithFetch(path);
};

//下载模板
const downloadTemplate = async () => {
  const url = import.meta.env.VITE_BASE_URL + '/template/ToDo模板.xlsx';
  console.log(111111111, url);
  downloadFileWithFetch(url);
};
</script>

<style lang="less" scoped>
.download-template {
  color: rgb(56, 189, 199);
  cursor: pointer;
  width: 100%;
  text-align: center;
}
</style>
